//
//  FriendCircleCommentView.m
//  CodeExamples
//
//  Created by letian on 16/12/6.
//  Copyright © 2016年 cmsg. All rights reserved.
//

#import "FriendCircleCommentView.h"
#import "FriendCircleCommentModel.h"
#import "FriendCircleLikeModel.h"
#import "MLLinkLabel.h"

@interface FriendCircleCommentView ()<MLLinkLabelDelegate>

@property (nonatomic, strong) NSArray *likeItemsArray;
@property (nonatomic, strong) NSArray *commentItemsArray;

@property (nonatomic, strong) UIImageView *bgImageView;

@property (nonatomic, strong) MLLinkLabel *likeLabel;
@property (nonatomic, strong) UIView *likeLableBottomLine;

@property (nonatomic, strong) NSMutableArray *commentLabelsArray;

@end

@implementation FriendCircleCommentView

- (instancetype)init
{
    self = [super init];
    if (self) {
        [self setupUI];
        [self setConstant];
    }
    return self;
}

- (void)awakeFromNib
{
    [super awakeFromNib];
    [self setupUI];
    [self setConstant];
}

#pragma mark - 设置UI
- (void)setupUI
{
    _bgImageView = [LTUITools lt_creatImageView];
    UIImage *bgImage = [[[UIImage imageNamed:@"LikeCmtBg"] stretchableImageWithLeftCapWidth:40 topCapHeight:30] imageWithRenderingMode:UIImageRenderingModeAutomatic];
    _bgImageView.image = bgImage;
    _bgImageView.backgroundColor = [UIColor clearColor];
    [self addSubview:_bgImageView];
    
    _likeLabel = [MLLinkLabel new];
    _likeLabel.numberOfLines = 0;
    _likeLabel.font = [UIFont systemFontOfSize:14];
    _likeLabel.linkTextAttributes = @{NSForegroundColorAttributeName : RGBCOLOR(92,140,193)};
    [self addSubview:_likeLabel];
    
    _likeLableBottomLine = [LTUITools lt_creatView];
    [self addSubview:_likeLableBottomLine];

}

#pragma mark - 设置约束
- (void)setConstant
{
    
    [_bgImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self).offset(0);
    }];
    
}


- (void)viewDataWithLikeItemsArray:(NSArray *)likeItemsArray commentItemsArray:(NSArray *)commentItemsArray
{
    self.likeItemsArray = likeItemsArray;
    self.commentItemsArray = commentItemsArray;
    
    if (self.commentLabelsArray.count) {
        [self.commentLabelsArray enumerateObjectsUsingBlock:^(UILabel *label, NSUInteger idx, BOOL *stop) {
            [label mas_remakeConstraints:^(MASConstraintMaker *make) {
                
            }];
            label.hidden = YES; //重用时先隐藏所以评论label，然后根据评论个数显示label
        }];
    }
    
    if (!self.likeItemsArray.count && !self.commentItemsArray.count) {
        [self mas_updateConstraints:^(MASConstraintMaker *make) {
            make.height.mas_equalTo(0);
        }];
        return;
    }
    
    CGFloat margin = 5;
    
    UIView *lastTopView = nil;
    //存在点赞人数
    if (self.likeItemsArray.count) {
        
        [_likeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self).offset(margin);
            make.right.equalTo(self).offset(-margin);
            make.top.equalTo(self).offset(10);
        }];
        lastTopView = _likeLabel;
    } else {
        lastTopView = self;
        _likeLabel.attributedText = nil;
        [_likeLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
            
        }];
    }
    
    
    if (self.commentItemsArray.count > 0 && self.likeItemsArray.count > 0) {
        [_likeLableBottomLine mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.left.right.equalTo(self).offset(0);
            make.top.equalTo(lastTopView.mas_bottom).offset(3);
            make.height.mas_equalTo(1);
        }];
        lastTopView = _likeLableBottomLine;
    } else {
        [_likeLableBottomLine mas_remakeConstraints:^(MASConstraintMaker *make) {
            
        }];
    }
    
    for (int i = 0; i < self.commentItemsArray.count; i++) {
        UILabel *label = (UILabel *)self.commentLabelsArray[i];
        label.hidden = NO;
        CGFloat topMargin = (i == 0 && self.likeItemsArray.count == 0) ? 10 : 5;
        
        [label mas_updateConstraints:^(MASConstraintMaker *make) {
            if (lastTopView == self) {
                make.top.equalTo(lastTopView).offset(topMargin);
            }else{
                make.top.equalTo(lastTopView.mas_bottom).offset(topMargin);
            }
            make.left.equalTo(self).offset(8);
            make.right.equalTo(self).offset(-5);
            
            
        }];
        
        lastTopView = label;
    }
    
    [self mas_updateConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(lastTopView.mas_bottom).offset(5);
    }];
}

- (void)setLikeItemsArray:(NSArray *)likeItemsArray
{
    _likeItemsArray = likeItemsArray;
    
    if (likeItemsArray == nil) {
        return;
    }
    
    NSTextAttachment *attach = [NSTextAttachment new];
    attach.image = [UIImage imageNamed:@"Like"];
    attach.bounds = CGRectMake(0, -3, 16, 16);
    NSAttributedString *likeIcon = [NSAttributedString attributedStringWithAttachment:attach];
    
    NSMutableAttributedString *attributedText = [[NSMutableAttributedString alloc] initWithAttributedString:likeIcon];
    
    for (int i = 0; i < likeItemsArray.count; i++) {
        FriendCircleLikeModel *model = likeItemsArray[i];
        if (i > 0) {
            [attributedText appendAttributedString:[[NSAttributedString alloc] initWithString:@"，"]];
        }
        if (!model.attributedContent) {
            model.attributedContent = [self generateAttributedStringWithLikeItemModel:model];
        }
        [attributedText appendAttributedString:model.attributedContent];
    }
    
    _likeLabel.attributedText = [attributedText copy];
}

- (void)setCommentItemsArray:(NSArray *)commentItemsArray
{
    _commentItemsArray = commentItemsArray;
    
    long originalLabelsCount = self.commentLabelsArray.count;
    long needsToAddCount = commentItemsArray.count > originalLabelsCount ? (commentItemsArray.count - originalLabelsCount) : 0;
    for (int i = 0; i < needsToAddCount; i++) {
        MLLinkLabel *label = [MLLinkLabel new];
        UIColor *highLightColor = RGBCOLOR(92,140,193);
        label.linkTextAttributes = @{NSForegroundColorAttributeName : highLightColor};
        label.font = [UIFont systemFontOfSize:14];
        label.numberOfLines = 0;
        label.dataDetectorTypes = MLDataDetectorTypeAll;
        label.delegate = self;
        [self addSubview:label];
        [self.commentLabelsArray addObject:label];
    }
    
    for (int i = 0; i < commentItemsArray.count; i++) {
        FriendCircleCommentModel *model = commentItemsArray[i];
        MLLinkLabel *label = self.commentLabelsArray[i];
        if (!model.attributedContent) {
            model.attributedContent = [self generateAttributedStringWithCommentItemModel:model];
        }
        label.attributedText = model.attributedContent;
    }
}

///设置评论富文本
- (NSMutableAttributedString *)generateAttributedStringWithCommentItemModel:(FriendCircleCommentModel *)model
{
    NSString *text = model.firstUserName;
    if (model.secondUserName.length) {
        text = [text stringByAppendingString:[NSString stringWithFormat:@"回复%@", model.secondUserName]];
    }
    text = [text stringByAppendingString:[NSString stringWithFormat:@"：%@", model.commentString]];
    NSMutableAttributedString *attString = [[NSMutableAttributedString alloc] initWithString:text];
    [attString setAttributes:@{NSLinkAttributeName : model.firstUserId} range:[text rangeOfString:model.firstUserName]];
    if (model.secondUserName) {
        [attString setAttributes:@{NSLinkAttributeName : model.secondUserId} range:[text rangeOfString:model.secondUserName]];
    }
    return attString;
}

///设置喜欢富文本
- (NSMutableAttributedString *)generateAttributedStringWithLikeItemModel:(FriendCircleLikeModel *)model
{
    NSString *text = model.userName;
    NSMutableAttributedString *attString = [[NSMutableAttributedString alloc] initWithString:text];
    UIColor *highLightColor = [UIColor lightGrayColor];
    [attString setAttributes:@{NSForegroundColorAttributeName : highLightColor, NSLinkAttributeName : model.userId} range:[text rangeOfString:model.userName]];
    
    return attString;
}

#pragma mark - MLLinkLabelDelegate

- (void)didClickLink:(MLLink *)link linkText:(NSString *)linkText linkLabel:(MLLinkLabel *)linkLabel
{
    NSLog(@"%@", link.linkValue);
}

#pragma mark - getter
- (NSMutableArray *)commentLabelsArray
{
    if (!_commentLabelsArray) {
        _commentLabelsArray = [NSMutableArray new];
    }
    return _commentLabelsArray;
}

@end
